import { Component } from "react";
import { TreeSelect } from "antd";
import { deepTree } from "@/utils";
import { getMenuList } from "@/api/menu";

interface IProps {
  value?: number;
  onChange?: (value: number) => void;
}

interface IState {
  treeData: Menu.Item[];
}

export default class MenuSelect extends Component<IProps, IState> {
  // 初始化 state
  state: Readonly<IState> = {
    treeData: [],
  };

  // 刷新
  refresh = () => {
    getMenuList().then((resp) => {
      const tree = deepTree(resp.filter((item) => item.type !== 2));
      // 赋值给 treeData
      this.setState({
        treeData: tree,
      });
    });
  };

  render() {
    const {
      props: { value, onChange },
      state: { treeData },
    } = this;

    return (
      <TreeSelect
        style={{ width: 200 }}
        placeholder="请选择"
        treeDefaultExpandAll
        fieldNames={{ value: "id", label: "name", children: "children" }}
        value={value}
        onChange={onChange}
        treeData={treeData}
      />
    );
  }

  componentDidMount(): void {
    this.refresh();
  }
}
